import * as echarts from 'echarts';
import { useRef, useEffect, useState } from "react"
const BarCharts = ({ title, className, XaxisData }) => {
    const homeRef = useRef(null)
    let [defualtXaxisData, setDefualtXaxisData] = useState(
        XaxisData && XaxisData[0].like_count > 0 && XaxisData.length >= 2 ?
            XaxisData.map(item => item.like_count) :
            [0]
    )
    let [defaultTitleData, setDefaultTitleData] = useState(
        XaxisData && XaxisData[0].like_count > 0 && XaxisData.length >= 2 ?
            XaxisData.map(item => item.title) :
            ['无点赞数据']
    )

    const drawChart = () => {

        const myCharts = echarts.init(homeRef.current)
        const option = {
            title: {
                text: title
            },
            tooltip: {
                show: true,
                trigger: 'item',
                formatter: function (params) {
                    return `文章名称:${params.name}<br/>文章点赞量:${params.data}`
                }
            },
            xAxis: {
                type: 'category',
                data: defaultTitleData
            },
            yAxis: {
                type: 'value',
                min: 0,
                max: 200
            },
            series: [
                {
                    data: defualtXaxisData,
                    type: 'bar',

                }
            ]
        }

        myCharts.setOption(option)
        return () => {
            myCharts.dispose();
        };
    }

    useEffect(() => {
        drawChart()

    }, [XaxisData])

    return (
        <div ref={homeRef} className={className}></div>
    )
}
export default BarCharts